#coding=utf-8

from rest_framework.views import exception_handler
from rest_framework.response import Response
import logging
from django.core.serializers.json import json
import requests
from django.db.models import Q
import time
from content.models import Navigation
import uuid

def to_UUID(s):
    """将字符串转化为uuid"""
    try:
        id = uuid.UUID(s)
    except:
        return None
    else:
        return id

def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)
    # Now add the HTTP status code to the response.
    if response is not None:
        #response.data['status_code'] = response.status_code
        if response.data.has_key("detail"):
            return res(-response.status_code, response.data["detail"])
    return response

def res(code = 0, msg = '', data = None):
    da = {}
    da['code'] = code
    da['msg'] = msg
    da['data'] = data
    return Response(da)

def log(msg):
    log = logging.getLogger('default')
    log.info(json.dumps(msg))

from random import Random
def random_str(randomlength=8):
    str = ''
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    length = len(chars) - 1
    random = Random()
    for i in range(randomlength):
        str+=chars[random.randint(0, length)]
    return str

def random_numberstr(randomlength=8):
    str = ''
    chars = '123456789'
    length = len(chars) - 1
    random = Random()
    for i in range(randomlength):
        str+=chars[random.randint(0, length)]
    return str

def phonecheck(s):
    #号码前缀，如果运营商启用新的号段，只需要在此列表将新的号段加上即可。
    #phoneprefix=['130','131','132','133','134','135','136','137','138','139','150','151','152','153','156','158','159','170','183','182','185','186','188','189']
    #检测号码是否长度是否合法。
    if len(s)<>11:
        return False
    else:
        #检测输入的号码是否全部是数字。
        if  s.isdigit():
            #检测前缀是否是正确。
            return True
            #if s[:3] in phoneprefix:
            #    return True
            #else:
            #    return False
        else:
            return False

def send_sms(mobile, codestr):
    """短信发送接口"""
    resp = requests.post("http://sms-api.luosimao.com/v1/send.json",
    auth=("api", "key-dbd8b45e266912b0d2736158e70d7251"),
    data={
        "mobile": mobile,
        "message": codestr
    },timeout=3 , verify=False)
    result =  json.loads( resp.content )
    return result

def passwordcheck(password):
    if len(password) < 6:
        return False
    else:
        return True

def StandardList(request, serializer_class, queryset):
    pagesize = 20
    page = 1
    if request.query_params.has_key("page"):
        page = int(request.query_params["page"])
    if request.query_params.has_key("pagesize"):
        pagesize = int(request.query_params["pagesize"])

    serializer = serializer_class(queryset[pagesize*(page-1): pagesize*page], many=True)
    da = {}
    da['results'] = serializer.data
    total = queryset.count()
    da['count'] = total
    if pagesize == 0:
        return da

    pages_count = total/pagesize
    if total != pages_count * pagesize:
        pages_count += 1

    next_page = page + 1
    previous_page = page - 1
    if next_page > pages_count:
        next_page = None
    if previous_page < 1:
        previous_page = None
    da['next'] = next_page
    da['previous'] = previous_page

    return da


def get_basecontent_queryset(queryset, request, Q_key = None):
    """筛选基础内容"""
    query = queryset.filter(isEnabled = True)

    if request.query_params.has_key("nav_id"):
        query = query.filter(nav_id = request.query_params["nav_id"])

    if request.query_params.has_key("company_id"):
        company_id = request.query_params["company_id"]
        company_nav = Navigation.objects.filter(company_id = company_id).filter(isShow = True).values_list('id', flat=True)
        query = query.filter(nav_id__in = company_nav)

    if request.query_params.has_key("key"):
        key = request.query_params["key"]
        Q_params = Q(id = to_UUID(key)) | Q(name__contains = key) | Q(title__contains = key) | Q(des__contains = key) | Q(keywords__contains = key)

        if Q_key:
            Q_params = Q_params | Q_key

        query = query.filter(Q_params)

    if request.query_params.has_key("created_at_gte"):
        """时间格式固定为：'2015-12-21 15:01:28' """
        created_at_gte = datetime.datetime.strptime(request.query_params["created_at_gte"], '%Y-%m-%d %H:%M:%S')
        query = query.filter(created_at__gte = created_at_gte)

    if request.query_params.has_key("created_at_gt"):
        """时间格式固定为：'2015-12-21 15:01:28' """
        created_at_gt = datetime.datetime.strptime(request.query_params["created_at_gt"], '%Y-%m-%d %H:%M:%S')
        query = query.filter(created_at__gt = created_at_gt)

    if request.query_params.has_key("created_at_lte"):
        """时间格式固定为：'2015-12-21 15:01:28' """
        created_at_lte = datetime.datetime.strptime(request.query_params["created_at_lte"], '%Y-%m-%d %H:%M:%S')
        query = query.filter(created_at__lte = created_at_lte)

    if request.query_params.has_key("created_at_lt"):
        """时间格式固定为：'2015-12-21 15:01:28' """
        created_at_lt = datetime.datetime.strptime(request.query_params["created_at_lt"], '%Y-%m-%d %H:%M:%S')
        query = query.filter(created_at__lt = created_at_lt)

    if request.query_params.has_key("updated_at_gte"):
        """时间格式固定为：'2015-12-21 15:01:28' """
        updated_at_gte = datetime.datetime.strptime(request.query_params["updated_at_gte"], '%Y-%m-%d %H:%M:%S')
        query = query.filter(updated_at__gte = updated_at_gte)
    
    if request.query_params.has_key("updated_at_gt"):
        """时间格式固定为：'2015-12-21 15:01:28' """
        updated_at_gt = datetime.datetime.strptime(request.query_params["updated_at_gt"], '%Y-%m-%d %H:%M:%S')
        query = query.filter(updated_at__gt = updated_at_gt)

    if request.query_params.has_key("updated_at_lte"):
        """时间格式固定为：'2015-12-21 15:01:28' """
        updated_at_lte = datetime.datetime.strptime(request.query_params["updated_at_lte"], '%Y-%m-%d %H:%M:%S')
        query = query.filter(updated_at__lte = updated_at_lte)
    
    if request.query_params.has_key("updated_at_lt"):
        """时间格式固定为：'2015-12-21 15:01:28' """
        updated_at_lt = datetime.datetime.strptime(request.query_params["updated_at_lt"], '%Y-%m-%d %H:%M:%S')
        query = query.filter(updated_at__lt = updated_at_lt)

    if request.query_params.has_key("click_count_gte"):
        click_count_gte = int(request.query_params["click_count_gte"])
        query = query.filter(click_count__gte = click_count_gte)

    if request.query_params.has_key("click_count_gt"):
        click_count_gt = int(request.query_params["click_count_gt"])
        query = query.filter(click_count__gt = click_count_gt)

    if request.query_params.has_key("click_count_lte"):
        click_count_lte = int(request.query_params["click_count_lte"])
        query = query.filter(click_count__lte = click_count_lte)

    if request.query_params.has_key("click_count_lt"):
        click_count_lt = int(request.query_params["click_count_lt"])
        query = query.filter(click_count__lt = click_count_lt)

    return query
    

    


    
